from wormbane.ui.selection_dialog import selection_dialog

import random

def command_wield(game, ui):
    wieldable = [thing for thing in game.hero.inv
                 if (thing.is_item and not thing.wielded
                     and (not thing.is_armor or not thing.worn))]
    if game.hero.weapon:
        wieldable.append('nothing')
    if not wieldable:
        game.write(game.hero, 'has nothing to wield')
        return
    wieldable.reverse()

    if len(wieldable) == 1:
        selection = set(wieldable)
    else:
        selection = selection_dialog(ui.stdscr, wieldable, prompt = 'Wield')
        if not selection:
            game.write('Never mind.')
            return

    if game.hero.weapon and game.hero.weapon.cursed:
        game.write(game.hero, 'cannot stop wielding', game.hero.weapon)
        game.hero.weapon.beatitude_id = True
    item = random.choice(list(selection))
    if item == 'nothing':
        old = game.hero.weapon
        game.hero.wield(None)
        game.write(game.hero, 'stops wielding', old)
        old.merge()
    else:
        item = item.split()
        old = game.hero.weapon
        if old:
            game.hero.wield(None)
        game.hero.wield(item)
        if item.is_weapon:
            item.enchantment_id = True
        game.write(game.hero, 'wields', item)
        if old:
            old.merge()
    game.hero_moved = True
